#include "message.hpp"
#include "net.hpp"
#include "dispatcher.hpp"

//如果采用RpcRequest类型不一致
//接口装傻子，内部次啊用dynamic_pointer_cast进行转化
//怕跟创建类型，对应不上-->感觉不完美，想外部简单点->采用模板
//那么这里在dispatcher回调函数进行处理，搞一个模板
void onRpcRequest(const bitrpc::BaseConnection::ptr& conn, bitrpc::RpcRequest::ptr& msg){
    std::cout << "收到了Rpc请求:" << msg->method() <<std::endl;
    std::string body = msg->serialize(); //进行序列化
    std::cout << body << std::end();
    std::cout << "method:" << msg->method() << std::endl;
    
    //创建响应工厂类
    auto rpc_req = bitrpc::BaseMessageFactory::create<bitrpc::RpcResponse>();
    rpc_req->setId("1111");
    rpc_req->setMtype(bitrpc::MType::RSP_RPC);
    rpc_req->setRCode(bitrpc::RCode::RCODE_OK);
    rpc_req->setResult(33);
    conn->send(rpc_req);
}

void onTopicRequest(const bitrpc::BaseConnection::ptr& conn, bitrpc::BaseMessage::ptr& msg){
    std::cout << "收到了Topic请求:";
    std::string body = msg->serialize(); //进行序列化
    std::cout << body << endl;

    //创建响应工厂类
    auto rpc_req = bitrpc::BaseMessageFactory::create<bitrpc::TopicResponse>();
    rpc_req->setId("1111");
    rpc_req->setMtype(bitrpc::MType::SRP_TOPIC);
    rpc_req->setRCode(bitrpc::RCode::RCODE_OK);
    rpc_req->setResult(33);
    conn->send(rpc_req);
}


int main()
{
    //1. 先注册
    auto dispatcher = std::make_shared<bitrpc::Dispatcher>();
    dispatcher->registerHandler(bitrpc::MType::REQ_RPC, onRpcResponse); //注册映射
    dispatcher->registerHandler(bitrpc::MType::REQ_TOPIC, onTopicResponse); //注册映射

    //2.创建对象，绑定回调函数
    auto server = bitrpc::ServerFactory::create(9090);
    auto message_cb = std::bind(&bitrpc::Dispatcher::onMessage, dispatcher.get(),
                        std::placeholders_1, std::placeholders_2);
    //3.设置回调函数
    server->setMessageCallback(message_cb); //设置回调函数
    server.start(); //开始处理
    return 0;
}